from django.core.paginator import PageNotAnInteger
from django.shortcuts import render
from django.views.generic.base import View
from pure_pagination import Paginator

from apps.blogmessage.models import BlogMessage, BlogTag, AboutMessage
from apps.users.models import UserProfile


# Create your views here.


class IndexView(View):
    def get(self, request, *args, **kwargs):
        user = UserProfile.objects.get(id=1)
        message_all = BlogMessage.objects.all().order_by('-add_time')
        new_messages = message_all.order_by('-add_time')[0:10]
        tags = BlogTag.objects.all()
        search_type = 'index'
        try:
            page = request.GET.get('page', 1)
        except PageNotAnInteger:
            page = 1
        # 分页
        p = Paginator(message_all, per_page=10, request=request)
        messages = p.page(page)
        return render(request, 'index.html', {
            'user': user,
            'messages': messages,
            'new_messages': new_messages,
            'search_type': search_type,
            'tags': tags
        })


class Gui_DangView(View):
    def get(self, request, *args, **kwargs):

        message_all = BlogMessage.objects.all()
        guidang_messages = message_all.order_by('-add_time')
        search_type = 'gui_dang'
        new_messages = message_all.order_by('-add_time')[0:10]
        tags = BlogTag.objects.all()
        try:
            page = request.GET.get('page', 1)
        except PageNotAnInteger:
            page = 1
        p = Paginator(guidang_messages, 10000, request=request)
        guidang_messages = p.page(page)
        return render(request, 'gui_dang.html', {
            'new_messages': new_messages,
            'search_type': search_type,
            'tags': tags,
            'guidang_messages':guidang_messages
        })


class AboutView(View):
    def get(self, request, *args, **kwargs):
        about = AboutMessage.objects.get(id=1)
        message_all = BlogMessage.objects.all()
        about.click_nums += 1
        about.save()
        search_type = 'about'
        tags = BlogTag.objects.all()
        new_messages = message_all.order_by('-add_time')[0:10]
        return render(request, 'about.html', {
            'new_messages': new_messages,
            'search_type': search_type,
            'tags': tags,
            'about': about
        })
